package com.example.testapp.activity.helper;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Entity;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;

import com.example.testapp.activity.model.ImageBucket;
import com.example.testapp.activity.model.ImageItem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by l on 2016/7/3.
 */
public class AlbumHelper {

    public final String TAG = getClass().getSimpleName();
    public Context context;
    public ContentResolver contentResolver;
    public static AlbumHelper mInstance = null;

    // 缩略图列表
    private HashMap<String, String> thumbnailList = new HashMap<String, String>();
    // 专辑列表
    private List<HashMap<String, String>> albumList = new ArrayList<HashMap<String, String>>();
    private HashMap<String, ImageBucket> bucketList = new HashMap<String, ImageBucket>();

    /**
     * 是否创建了图片集
     */
    boolean hasBuildImagesBucketList = false;

    public static AlbumHelper getHelper() {
        if (mInstance == null){
            mInstance = new AlbumHelper();
        }
        return mInstance;
    }

    public void init(Context context) {
        if(this.context == null){
            this.context = context;
            contentResolver = context.getContentResolver();
        }
    }

    /**
     * 得到图片集
     *
     * @param refresh
     * @return
     */
    public List<ImageBucket> getImagesBucketList(boolean refresh) {
        if(refresh || (!refresh && !hasBuildImagesBucketList)){
            buildImageBucketList();
        }
        List<ImageBucket> tmpList = new ArrayList<ImageBucket>();
        Iterator<Map.Entry<String, ImageBucket>> itr =  bucketList.entrySet().iterator();
        while (itr.hasNext()){
            Map.Entry<String, ImageBucket> entry = (Map.Entry<String, ImageBucket>)itr.next();
            tmpList.add(entry.getValue());
        }
        return tmpList;
    }

    /**
     * 得到图片集
     */
    private void buildImageBucketList() {
        long startTime = System.currentTimeMillis();
        // 构造缩略图索引
        getThumbnail();
        // 构造相册索引
        String columns[] = new String[]{MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
                 MediaStore.Images.Media.PICASA_ID, MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.TITLE,
                MediaStore.Images.Media.SIZE, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
        // 得到一个游标
        Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, null);
        if(cursor.moveToFirst()){
            int ID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int Path = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            int Name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
            int Title = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
            int Size = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
            int DisplayName = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
            int bucketIdIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID);
            int picasaIdIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.PICASA_ID);

            int totalNum = cursor.getCount();
            do {
                String _id = cursor.getString(ID);
                String path = cursor.getString(Path);
                String name = cursor.getString(Name);
                String title = cursor.getString(Title);
                String size = cursor.getString(Size);
                String bucketName = cursor.getString(DisplayName);
                String bucketId = cursor.getString(bucketIdIndex);
                String picasaId = cursor.getString(picasaIdIndex);

                Log.i(TAG, _id + ", bucketid: " + bucketId + ", picasaId: "
                        + picasaId + " name:" + name + " path:" + path
                        + " title: " + title + " size: " + size + " bucket: "
                        + bucketName + "---");
                ImageBucket bucket = bucketList.get(bucketId);
                if(bucket == null){
                    bucket = new ImageBucket();
                    bucketList.put(bucketId, bucket);
                    bucket.imageList = new ArrayList<>();
                    bucket.bucketName = bucketName;
                }
                bucket.count++;
                ImageItem imageItem = new ImageItem();
                imageItem.imageId = _id;
                imageItem.imagePath = path;
                imageItem.thumbnailPath = thumbnailList.get(_id);
                bucket.imageList.add(imageItem);
            }while (cursor.moveToNext());
        }
          Iterator<Map.Entry<String, ImageBucket>> itr = bucketList.entrySet().iterator();
        while (itr.hasNext()){
            Map.Entry<String, ImageBucket> entry = itr.next();
            ImageBucket bucket = entry.getValue();
            Log.d(TAG, entry.getKey() + ", " + bucket.bucketName + ", "
                    + bucket.count + " ---------- ");
            for (int i = 0; i<bucket.imageList.size(); i++){
                ImageItem image = bucket.imageList.get(i);
                Log.d(TAG, "----- " + image.imageId + ", " + image.imagePath
                        + ", " + image.thumbnailPath);
            }
        }
        hasBuildImagesBucketList = true;
        long endTime = System.currentTimeMillis();
        Log.d(TAG, "use time: " + (endTime - startTime) + " ms");
    }

    /**
     * 得到缩略图
     */
    private void getThumbnail() {
        String[] projection = {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails.DATA};
        Cursor cursor = contentResolver.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null);
        getThumbnailColumnData(cursor);
    }

    /**
     * 从数据库中得到缩略图
     *
     * @param cur
     */
    private void getThumbnailColumnData(Cursor cur) {
       if(cur.moveToFirst()){
           int _id;
           int image_id;
           String image_path;
           int _idColumn = cur.getColumnIndex(MediaStore.Images.Thumbnails._ID);
           int image_idColumn = cur.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
           int dataColumn = cur.getColumnIndex(MediaStore.Images.Thumbnails.DATA);

           do {
               _id = cur.getInt(_idColumn);
               image_id = cur.getInt(image_idColumn);
               image_path = cur.getString(dataColumn);
               thumbnailList.put(" "+ image_id, image_path);
           }while (cur.moveToNext());
       }
    }
}
